<template>
  <div class="virtual-user-form">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <div class="avatar-upload-section">
          <self-upload
            ref="avatarUpload"
            v-model="form.avatar"
            :multiple="false"
          />
          <div class="upload-tip">支持jpg、png格式，建议尺寸100x100px</div>
        </div>
      </el-form-item>

      <!-- 用户名称 -->
      <el-form-item label="名称" prop="playerName">
        <el-input
          v-model="form.playerName"
          placeholder="请输入用户名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <!-- 国家 -->
      <el-form-item label="国家" prop="country">
        <el-input
          v-model="form.country"
          placeholder="请输入国家"
          maxlength="50"
        />
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import selfUpload from '@/components/base/selfUpload.vue'

export default {
  name: 'VirtualUserForm',
  components: {
    selfUpload
  },
  props: {
    formData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        playerName: '',
        country: '中国',
        avatar: ''
      },
      rules: {
        playerName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 1, max: 50, message: '名称长度在1到50个字符', trigger: 'blur' }
        ],
        country: [
          { required: true, message: '请输入国家', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    formData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.form = {
            ...this.form,
            ...newVal
          }
          // 强制更新头像组件
          this.$nextTick(() => {
            if (this.$refs.avatarUpload) {
              this.$refs.avatarUpload.image = newVal.avatar || '';
            }
          });
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {


    // 表单验证
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            resolve(this.form)
          } else {
            reject('表单验证失败')
          }
        })
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.form.resetFields()
      this.form = {
        playerName: '',
        country: '中国',
        avatar: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.virtual-user-form {
  padding: 20px;
}

.avatar-upload-section {
  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
}

:deep(.el-date-editor) {
  width: 100%;
}
</style>
